/**  
 * All rights Reserved, Designed By www.xiaozhanjiaoyu.cn
 * @Title:  SpeechSynthesizer.java   
 * @Package javaapplication.speechsynthesizer   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: knight.lu     
 * @date:   2018年11月21日 下午1:27:42   
 * @version V1.0 
 * @Copyright: 2018 www.xiaozhanjiaoyu.cn Inc. All rights reserved. 
 * 
 */
package com.tts.speechsynthesizer;

import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.OutputFormatEnum;
import com.alibaba.nls.client.protocol.SampleRateEnum;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizer;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerListener;
import com.component.AliAuthService;

/**   
 * @ClassName:  SpeechSynthesizer   
 * @Description:语音合成（TTS）  
 * @author: knight.lu 
 * @date:   2018年11月21日 下午1:27:42   
 *     
 */
public class SpeechSynthesizeHandler {
	    
	    private SpeechSynthesizerListener listener;
	    
	    private NlsClient client;
	    
	    
	    public SpeechSynthesizeHandler(SpeechSynthesizerListener listener) {
	        //this.listener = listener;
	    	this.listener = listener;
	        // Step0 创建NlsClient实例,应用全局创建一个即可,默认服务地址为阿里云线上服务地址
	        client = AliAuthService.createClient();
	    }

	    public void process(String requestText) {
	        SpeechSynthesizer synthesizer = null;
	        try {
	            // Step1 创建实例,建立连接
	            synthesizer = new SpeechSynthesizer(client, this.listener);
	            synthesizer.setAppKey(AliAuthService.APP_KEY);
	            // 设置返回音频的编码格式
	            synthesizer.setFormat(OutputFormatEnum.WAV);
	            // 设置返回音频的采样率
	            synthesizer.setSampleRate(SampleRateEnum.SAMPLE_RATE_16K);
	            // 设置用于语音合成的文本
	            synthesizer.setText(requestText);

	            // Step2 此方法将以上参数设置序列化为json发送给服务端,并等待服务端确认
	            synthesizer.start();
	            // Step3 等待语音合成结束
	            synthesizer.waitForComplete();
	            //4 通知合成完成播放
	            
	        } catch (Exception e) {
	            System.err.println(e.getMessage());
	        } finally {
	            // Step4 关闭连接
	            if (null != synthesizer) {
	                synthesizer.close();
	            }
	        }
	    }

	    public void shutdown() {
	        client.shutdown();
	    }

}
